package com.edu.whty.common.tools;

import com.edu.whty.common.constants.AdminConstant;
import com.edu.whty.entity.system.SessionUser;
import com.edu.whty.entity.teacherassistant.*;
import com.whty.apigateway.security.EncryptionUtils;
import com.whty.apigateway.security.login.EncryptUtils;
import com.whty.apigateway.security.login.MD5Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * 点滴教育云登录
 * @author liuf
 *
 */
public class TeaHelpUtils {
	
	/**
	 * 武汉教育云登录加密：
	 * 静态密码加密方式：MD5加密后字母字符为大写的字符串，
	 * 再经过RC4加密(加密的密钥user_sercretkey)；
	 * 密码经过加密后再传输
	 */
	public static final String USER_SERCRETKEY = "user_sercretkey";
	
	/**
	 * 存储key
	 */
	public static final String TOKEN_KEY = "peronnal_token_key";

	private static Logger logger = LoggerFactory.getLogger(TeaHelpUtils.class);
	
	private static Properties properties = new Properties();
	
	private static final String eduyunCfg = "system.properties";
	
	/**
	 * 点滴教育云appid
	 */
	public static final String APP_ID = "appId";
	
	/**
	 * 点滴教育云appKey
	 */
	public static final String APP_KEY = "appKey";
	
	/**
	 * 点滴教育云登录接口地址
	 */
	public static final String EDUYUN_LOGIN_URL = "ddjyy_login_url";
	
	/**
	 * 点滴教育云获取token接口地址
	 */
	public static final String GET_TOKEN_URL = "get_token_url";
	/**
	 * 点滴教育云根据usessionid获取用户信息
	 */
	public static final String GET_USERINFO_BY_USESSIONID = "get_userinfo_by_usessionid";
	/**
	 * 点滴教育云公共头尾获取
	 */
	public static final String COMMONHTML_URL = "commonhtml_url";
	/**
	 * 点滴教育云工作空间
	 */
	public static final String WORK_SPACE = "work_space";
	/**
	 * 成功状态
	 */
	public static final String SUCCESS_CODE = "000000";
	/**
	 * 头像大小类型 1：小 2：中 3：大
	 */
	public static final String USER_LOGO_MID = "2";
	/**
	 * 点滴教育云域名（供头像使用）
	 */
	public static final String DDJYY_EDUYUN_DOMAIN = "ddjyy_eduyun_domain";
	/**
	 * 查询学段 - 1.1.1
	 */
	public static final String QUERY_PERIODS = "query_periods";
	/**
	 * 查询学段 - 1.1.2
	 */
	public static final String QUERY_SUBJECTS = "query_subjects";
	/**
	 * 查询版本 - 1.1.3
	 */
	public static final String QUERY_EDITIONS = "query_editions";
	/**
	 * 查询年级 - 1.1.4
	 */
	public static final String QUERY_GRADES = "query_grades";
	/**
	 * 查询年级 - 1.1.5
	 */
	public static final String QUERY_VOLUMES = "query_volumes";
	/**
	 * 查询教材 - 1.1.6
	 */
	public static final String QUERY_TEXTBOOKS = "query_textbooks";
	/**
	 * 查询章节 - 1.1.7
	 */
	public static final String QUERY_CHAPTERS = "query_chapters";
	
	public static final String RESOURCE_DETAIL = "resourceDetail";
	
	/**
	 * 查询资源列表 - 1.3.2
	 */
	public static final String QUERY_RESOURCELIST = "query_resourceList";
	
	/**
	 * 教材资源下载
	 */
	public static final String DOWNLOAD_TEXTBOOKS = "download_textbooks";
	
	/**
	 * 限制下载资源的最大数量
	 */
	public static final String LIMIT_DOWNLOAD = "limit_download";
	
	/**
	 * 文件上传时的orgid
	 */
	public static final String ORGID = "orgid";
	
	/**
	 * 上传文件- 1.2.1
	 */
	public static final String UPLOADIFY = "uploadify";
	
	/**
	 * 资源创建- 1.3.4
	 */
	public static final String CREATERESOURCE ="createResource";
	
	/**
	 * 上传电子教材文件，本地临时保存目录
	 */
	public static final String FILE_UPLOAD_PATH = "file_upload_path";
	
	/**
	 * 查询微课资源的播放地址
	 */
	public static final String QUERY_PREVIEW = "query_preview";
	
	static {
		try {
			if(properties.isEmpty()){
				InputStream is = SysConfig.class.getClassLoader().getResourceAsStream(eduyunCfg);
				properties.load(is);
			}
			logger.info("加载文件目录配置'" + eduyunCfg + "'成功！");
		} catch (FileNotFoundException e) {
			logger.error("文件目录配置文件不存在！",e);
		} catch (IOException e) {
			logger.error("读取文件目录配置文件IO错误！",e);
		}
	}
	
	/**
	 * 获取属性值
	 * @param key
	 * @return
	 */
	public static String getProperty(String key){
		return properties.getProperty(key);
	}
	
	
	/*********************************下面为教育云接口*************************************************/
	
	/**
	 * 对明文进行加密
	 * @param password
	 * @return
	 */
	public static String encodePassword(String password){
		String passwd = MD5Utils.toMD5(password);
		EncryptUtils eu = EncryptUtils.getInstance();
		String encodepassword = eu.encode(passwd, USER_SERCRETKEY);
		return encodepassword;
	}
	
	/**
	 * 登录教育云，返回用户信息
	 */
	public static SessionUser getEduyunLoginInfo(HttpServletRequest request, String account, String password) {
		SessionUser sessionUser = null;
		String resp = null;

		JSONObject jsonb = new JSONObject();
		jsonb.put("account", account);
		jsonb.put("password", password);
		jsonb.put("portaltype", 0);
		jsonb.put("passwdtype", 99);
		//查询token
		String tokenstr = getAppToken(request);
		if(tokenstr == null){
			logger.error("获取token异常");
			return null;
		}
		
		// 登录接口
		try {
			String netIp=null==request.getAttribute("netIp")?null:request.getAttribute("netIp").toString();
			resp = HttpClientUtil.post(getProperty(EDUYUN_LOGIN_URL) + tokenstr, jsonb.toString(),netIp);
		} catch (Exception e) {
			logger.error("登录教育云平台异常： 请求url= " + getProperty(EDUYUN_LOGIN_URL)+
					" ，请求参数为：jsonb.toString()", e);
		}

		if(StringUtils.isNotEmpty(resp)){
			JSONObject  resultJSON = JSONObject.fromObject(resp);
			String resultCode = (String) resultJSON.get("result");
			if (SUCCESS_CODE.equalsIgnoreCase(resultCode)) {
				String usessionid = resultJSON.getString("usessionid");
				JSONObject userObj = resultJSON.getJSONObject("userinfo");
				
				//实体转换
				EduyunUserEntity userEntity = null;
				try {
					userEntity = (EduyunUserEntity) JsonUtils.jsonToObj(userObj.toString(),EduyunUserEntity.class);
				} catch (Exception e) {
					logger.error("教育云用户json转换为实体异常", e);
				}
				//转换教育云用户实体为 ---》 通用sessionuser
				sessionUser = getEbookSessionUser(userEntity);
				sessionUser.setUsessionid(usessionid);
			}else {
				logger.error("用户登录失败，返回信息为： "  + resp);
			}
		}
		
		return sessionUser;
	}
	
	/**
	 * 转换教育云用户实体为 ---》 通用sessionuser
	 * @param userEntity
	 * @return
	 */
	public static SessionUser getEbookSessionUser(EduyunUserEntity eduyunUserEntity){
		SessionUser sessionUser = null;
		if(eduyunUserEntity != null){
			sessionUser = new SessionUser();
			sessionUser.setUserId(eduyunUserEntity.getPersonid());
			sessionUser.setUserName(eduyunUserEntity.getAccount());
			sessionUser.setMobilePhone(eduyunUserEntity.getMobnum());
			sessionUser.setEmail(eduyunUserEntity.getEmail());
			sessionUser.setRealName(eduyunUserEntity.getName());
			sessionUser.setUserType(getEbookUserType(eduyunUserEntity.getUsertype()));
			sessionUser.setGender(eduyunUserEntity.getGender());
			sessionUser.setBirthday(eduyunUserEntity.getBirthday());
			sessionUser.setSchoolId(eduyunUserEntity.getOrgaid());
			sessionUser.setSchoolName(eduyunUserEntity.getOrganame());
			sessionUser.setClassId(eduyunUserEntity.getClassid());
			sessionUser.setClassName(eduyunUserEntity.getClassname());
			
			//头像
			List<UserLogo> userlogoList = eduyunUserEntity.getUserlogolist();
			if(userlogoList != null && userlogoList.size() > 0){
				for (int j = 0; j < userlogoList.size(); j++) {
					UserLogo userLogo = userlogoList.get(j);
					if(userLogo.getLogotype().equals(USER_LOGO_MID)){
						String url = getProperty(DDJYY_EDUYUN_DOMAIN) + userLogo.getLogourl();
						sessionUser.setUserLogoUrl(url);
					}
				}
			}
			
			//ebook 教师教学情况
			List<TeachingInfo> teachingInfoList = null;
			
			//登录用户为教师，则返回所教学科
			List<EduyunTeacheSubject> teachesubjectlist = eduyunUserEntity.getTeachesubjectlist();
			if(teachesubjectlist != null && teachesubjectlist.size() > 0){
				teachingInfoList = new ArrayList<TeachingInfo>();
				Map<String, Object> map = new HashMap<String, Object>();
				for (int i = 0; i < teachesubjectlist.size(); i++) {
					EduyunTeacheSubject ets = teachesubjectlist.get(i);
					String key = ets.getGrade() + "_" + ets.getSubjectid();
					if(map.containsKey(key)){
						continue;
					}
					map.put(key, key);
					TeachingInfo teachingInfo = new TeachingInfo();
					teachingInfo.setGradeId(ets.getGrade());
					teachingInfo.setSubjectId(ets.getSubjectid());
					teachingInfo.setSubjectName(ets.getSubjectname());
					teachingInfoList.add(teachingInfo);
				}
				
				//重新组合班级信息，设置到 上面的teachingInfoList
				for (int k = 0; k < teachingInfoList.size(); k++) {
					TeachingInfo ti = teachingInfoList.get(k);
					List<ClassInfo> classInfoList = new ArrayList<ClassInfo>();
					for (int j = 0; j < teachesubjectlist.size(); j++) {
						EduyunTeacheSubject ts = teachesubjectlist.get(j);
						//年级id，学科id相同，ClassInfo，添加班级信息
						if(StringUtil.isEmpty(ti.getGradeId()) || StringUtil.isEmpty(ts.getGrade())
								|| StringUtil.isEmpty(ti.getSubjectId()) || StringUtil.isEmpty(ts.getSubjectid())){
							continue;
						}
						
						if(ti.getGradeId().equals(ts.getGrade()) && 
								ti.getSubjectId().equals(ts.getSubjectid())){
							ClassInfo classInfo = new ClassInfo();
							classInfo.setClassId(ts.getClassid());
							classInfo.setClassName(ts.getClassname());
							classInfoList.add(classInfo);
						}
					}
					teachingInfoList.get(k).setClassList(classInfoList);
				}
			}
			sessionUser.setTeachingInfoList(teachingInfoList);
		}
		return sessionUser;
	}
	
	/**
	 * 教育云用户类型转化为ebook用户类型
	 * @param eduyunUserType 教育云用户类型
	 * @return
	 */
	public static String getEbookUserType(String eduyunUserType){
		String res = null;
		if(!StringUtil.isEmpty(eduyunUserType)){
			if("2".equals(eduyunUserType)){ //家长
				res = "5";
			}else if("4".equals(eduyunUserType)){ //学校
				res = "2";
			}else {
				res = eduyunUserType;
			}
		}
		return res;
	}
	
	/**
	 * ebook用户类型转化为教育云用户类型
	 * @param eduyunUserType 教育云用户类型
	 * @return
	 */
	public static String getEduyunUserType(String ebookUserType){
		String res = null;
		if(!StringUtil.isEmpty(ebookUserType)){
			if("5".equals(ebookUserType)){ //家长
				res = "2";
			}else if("2".equals(ebookUserType)){ //学校
				res = "4";
			}else {
				res = ebookUserType;
			}
		}
		return res;
	}
	
	/**
	 * 获取token，并存储到session中
	 * @param request
	 * @return
	 */
	public static String getAppToken(HttpServletRequest request){
		Long currentTime = System.currentTimeMillis();
		TokenInfo tokenInfo = null;
		HttpSession session = null;
		if(request != null){
			session = request.getSession();
			tokenInfo = (TokenInfo) session.getAttribute(TOKEN_KEY);
		}

		//校验token有效期，在有效期内，直接返回存在session中的token
		if (tokenInfo != null && tokenInfo.getValidtime() != null
				&& tokenInfo.getValidtime() > 0l
				&& tokenInfo.getValidtime() > currentTime) {
			return tokenInfo.getToken();
		}

		String digest = null;
		long timestamp = -1;
		try {
			JSONObject reqObj = new JSONObject();
			timestamp = System.currentTimeMillis();
			reqObj.put("appid", getProperty(APP_ID));
			reqObj.put("timestamp", timestamp);

			String paramValues = getProperty(APP_ID) + getProperty(APP_KEY) + timestamp;
			byte[] hmacSHA = EncryptionUtils.getHmacSHA1(paramValues,
					getProperty(APP_KEY));
			digest = EncryptionUtils.bytesToHexString(hmacSHA);
			digest = digest.toUpperCase();

			reqObj.put("keyinfo", digest);
			if(!logger.isDebugEnabled()){
				logger.info("查询请求URL:"+getProperty(GET_TOKEN_URL));
				logger.info("请求参数:"+reqObj.toString());
			}
			String netIp=null==request.getAttribute("netIp")?null:request.getAttribute("netIp").toString();
			String resp = HttpClientUtil.post(getProperty(GET_TOKEN_URL), reqObj.toString(),netIp);
			if(!logger.isDebugEnabled()){
				logger.info("token验证返回结果:"+resp);
			}
			if (StringUtils.isNotEmpty(resp)) {
				JSONObject  resultJSON = JSONObject.fromObject(resp);
				String resultCode = (String) resultJSON.get("result");
				if (SUCCESS_CODE.equalsIgnoreCase(resultCode)) {
					if(!logger.isDebugEnabled()){
						logger.info("查询token响应码为[" + resultCode + ",成功]");
					}
					tokenInfo = (TokenInfo)JSONObject.toBean(resultJSON.getJSONObject("tokenInfo"), TokenInfo.class);
					if (tokenInfo != null) {
						if(session != null){
							session.setAttribute(TOKEN_KEY, tokenInfo);
						}
						return tokenInfo.getToken();
					}
				} else {
					logger.error("查询token失败,appId:" + getProperty(APP_ID)
									+ ",appKey:" + getProperty(APP_KEY)
									+ ",timestamp:" + timestamp + ",keyinfo:"
									+ digest + ",返回值:" + resp);
				}
			}
		} catch (Exception e) {
			logger.error("查询token失败,appId:" + getProperty(APP_ID) + ",appKey:"
					+ getProperty(APP_KEY) + ",timestamp:" + timestamp
					+ ",keyinfo:" + digest + ",返回值:" + e.getMessage(), e);
		}
		return null;		
	}
	
	public static String  getUsessionId(HttpServletRequest request) {
		AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
		return principal.getName();
	}
	
	/**
	 * 点滴教育云： 通过usessionid查询用户信息
	 * @return
	 */
	public static SessionUser getDdjyyUserInfo(HttpServletRequest request) {
		SessionUser sessionUser = null;
		String token = getAppToken(request);
		JSONObject object = null;
		String usessionid = getUsessionId(request);
		
		if(!StringUtil.isEmpty(usessionid)){
			sessionUser = (SessionUser) request.getSession().getAttribute(AdminConstant.SESSION_USER);
			if(sessionUser!= null && usessionid.equals(sessionUser.getUsessionid())){
				sessionUser.setUserSource(AdminConstant.USER_SOURCE_DDJYY);
				return sessionUser;
			}
		}
		String netIp=null==request.getAttribute("netIp")?null:request.getAttribute("netIp").toString();
		try {
			@SuppressWarnings("unused")
			JSONObject reqObj = new JSONObject();
			String resp = HttpClientUtil.get(getProperty(GET_USERINFO_BY_USESSIONID) + usessionid + "?token=" + token,netIp);
			logger.info("根据usessionId获取用户信息返回 ="+resp+"usessionid="+usessionid);
			if (resp != null && !"".equals(resp)) {
				JSONObject obj = JSONObject.fromObject(resp);
				String resultCode = (String) obj.get("result");
				if (SUCCESS_CODE.endsWith(resultCode)) {
					object = (JSONObject) obj.get("userinfo");
					//实体转换
					EduyunUserEntity userEntity = null;
					try {
						userEntity = (EduyunUserEntity) JsonUtils.jsonToObj(object.toString(),EduyunUserEntity.class);
					} catch (Exception e) {
						logger.error("教育云用户json转换为实体异常", e);
					}
					//转换教育云用户实体为 ---》 通用sessionuser
					sessionUser = getEbookSessionUser(userEntity);
					sessionUser.setUsessionid(usessionid);
					sessionUser.setUserSource(AdminConstant.USER_SOURCE_DDJYY);
					if (StringUtil.isEmpty(sessionUser.getUserLogoUrl())) {
						String url = UploadFileUtil.getFilePath(UploadFileUtil.DEFAULT_USER_LOGO);
						sessionUser.setUserLogoUrl(url);
					}
					request.getSession().setAttribute(AdminConstant.SESSION_USER, sessionUser);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sessionUser;
	}
	
	/**
	 * 获取点滴教育云头尾
	 * @param request
	 * @param tag
	 * @return
	 */
	public static String getCommonHeaderAndFooter(HttpServletRequest request, String tag) {
		String commonUrlStrting = null;
		String tagResp = null;		
		try {
			String netIp=null==request.getAttribute("netIp")?null:request.getAttribute("netIp").toString();
			JSONObject bodyJson = new JSONObject();
			JSONObject paramsJson = new JSONObject();
			paramsJson.put("portaltype", 0);
			paramsJson.put("islogin", 1);
			paramsJson.put("usessionid", getUsessionId(request));
			paramsJson.put("areacode", "420100");
			paramsJson.put("type", tag);
			bodyJson.put("method", "commonHTML");
			bodyJson.put("params", paramsJson);
			Long currentTime = System.currentTimeMillis();
			tagResp = HttpClientUtil.post(getProperty(COMMONHTML_URL),bodyJson.toString(),netIp);
			if (!StringUtil.isEmpty(tagResp)) {
					JSONObject Obj = JSONObject.fromObject(tagResp);
					if (SUCCESS_CODE.equals(Obj.get("retCode"))) {
						JSONObject resultObj=(JSONObject) Obj.get("result");
							commonUrlStrting = (String) resultObj.get("sCommonContent");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return commonUrlStrting;
		
	}
	
	/**
	 * 头
	 * @return
	 */
	public static String getCommonHeader(HttpServletRequest request) {
		String commonHeader = getCommonHeaderAndFooter(request, "zoneHeader");
		request.getSession().setAttribute("commonHeader", commonHeader);
		return commonHeader;
	}
	
	/**
	 * 尾
	 * @return
	 */
	public static String getCommonFoot(HttpServletRequest request) {
		String commonFoot = getCommonHeaderAndFooter(request, "zoneFooter");
		request.getSession().setAttribute("commonFoot", commonFoot);
		return commonFoot;
	}
	
	public static void main(String[] args) {
		HttpServletRequest request = null;
		getEduyunLoginInfo(request, "1239710", encodePassword("1234qwer"));
	}
}
